package com.jml.service;


import com.jml.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.apache.skywalking.apm.toolkit.trace.TraceContext;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

@RestController
@Slf4j
public class MemberService {
    @Autowired
    private UserMapper userMapper;

    /**
     * 首页
     *
     * @return
     */
    @RequestMapping("/")
    public String myIndex() {
        return "...我是会员服务..";
    }

    /**
     *
     *
     * @param userName
     * @param userAge
     * @return
     */
    @RequestMapping("/insertUser")
    public String insertUser(String userName, Integer userAge) {
        // 获取request对象
        HttpServletRequest request = ((ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes()).getRequest();

        return userMapper.insertUser(userName, userAge) > 0 ? "success" : "fail";
    }

    /**
     * getUser
     *
     * @param age
     * @return
     */
    @RequestMapping("/getUser")
    public String getUser(int age) {
        int j = 1 / age;
        return j + "";
    }

    /**
     * 排除该请求不需要被追踪
     *
     * @return
     */
    @RequestMapping("/jmlExclude")
    public String jmlExclude() {
        return "jmlExclude";
    }


    /**
     * 模拟超时接口
     *
     * @return
     */
    @RequestMapping("/timeoutMember")
    public String timeoutMember() {
        try {
            Thread.sleep(3000);
        } catch (Exception e) {

        }
        return "success";
    }


    /**
     * 获取traceId
     * @return
     */
    @RequestMapping("/member")
    public String orderToMember() {
        // 获取request对象
        HttpServletRequest request = ((ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes()).getRequest();
        getHeders(request);
        // 获取traceId
        String traceId = TraceContext.traceId();
        log.info(">>traceId:{}<<", traceId);
        return "我是会员服务:" + traceId;
    }

    public static void getHeders(HttpServletRequest request) {
        //2.获得所有头的名称
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {//判断是否还有下一个元素
            String nextElement = headerNames.nextElement();//获取headerNames集合中的请求头
            String header2 = request.getHeader(nextElement);//通过请求头得到请求内容
            log.info("请求头=========={}" + nextElement + "VALUE:" + header2);
            //System.out.println(nextElement+":"+header2);
        }
    }
}
